package com.dewu.notify.api;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
@RequestMapping("/dingding")
public class DingDingTest {

	@Value("${dewu.notify.dingding}")
	private String dingdingUrl;

	@RequestMapping("/text")
	@ResponseBody
	public String sendText() {
		// #0. 配置钉钉客户端，dingdingUrl即根据刚才拷贝的Webhook
		DingTalkClient client = new DefaultDingTalkClient(this.dingdingUrl);

		// #1. request表示整个消息请求
		OapiRobotSendRequest request = new OapiRobotSendRequest();

		// #2. 请求设置 消息类别
		request.setMsgtype("text");

		// #3. 设置 消息内容
		OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();

		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String time = LocalDateTime.now() .format(formatter);

		text.setContent("得物来新订单了" + time);

		request.setText(text);

		// #4. 设置钉钉@功能
		OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
		at.setIsAtAll(true);
		request.setAt(at);

		try {
			// #5. 发送消息请求
			client.execute(request);

		} catch (ApiException e) {
			e.printStackTrace();
		}

		return "success";
	}
}
